package com.yamaha.bikemarket;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gcm.GCMRegistrar;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.sromku.simple.fb.Permissions;
import com.sromku.simple.fb.SimpleFacebook;
import com.sromku.simple.fb.SimpleFacebook.OnLoginListener;
import com.sromku.simple.fb.SimpleFacebook.OnLogoutListener;
import com.sromku.simple.fb.SimpleFacebookConfiguration;
import com.sromku.simple.fb.entities.Profile;
import com.yamaha.bikemarket.api.API;
import com.yamaha.bikemarket.util.CommonUtilities;
import com.yamaha.bikemarket.util.LogUtil;
import com.yamaha.bikemarket.util.SCStaticFunc;
import com.yamaha.bikemarket.util.Utils;

public class LoginFragment extends Activity {
	private SimpleFacebook simpleFacebook;

	private boolean isRegisterd = false;
	private final String TAG = getClass().getName();

	// private final BroadcastReceiver mHandleMessageReceiver = new
	// BroadcastReceiver() {
	// @Override
	// public void onReceive(Context context, Intent intent) {
	// String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
	// // Waking up mobile if it is sleeping
	// WakeLocker.acquire(getApplicationContext());
	//
	// /**
	// * Take appropriate action on this message depending upon your app
	// * requirement For now i am just displaying it on the screen
	// * */
	//
	// // Showing received message
	// Toast.makeText(getApplicationContext(),
	// "New Message: " + newMessage, Toast.LENGTH_LONG).show();
	//
	// // Releasing wake lock
	// WakeLocker.release();
	// }
	// };

	private AsyncTask<Void, Void, Void> mRegisterTask;

	private final Permissions[] permissions = new Permissions[] {
			Permissions.EMAIL, Permissions.USER_ABOUT_ME,
			Permissions.USER_ACTIVITIES, Permissions.USER_BIRTHDAY,
			Permissions.USER_EDUCATION_HISTORY, Permissions.USER_GROUPS,
			Permissions.USER_HOMETOWN, Permissions.USER_INTERESTS,
			Permissions.USER_LIKES, Permissions.USER_LOCATION,
			Permissions.USER_SUBSCRIPTIONS, Permissions.USER_WEBSITE,
			Permissions.USER_WORK_HISTORY, Permissions.USER_STATUS,
			Permissions.READ_STREAM, Permissions.READ_FRIENDLISTS,
			Permissions.USER_PHOTOS, Permissions.FRIENDS_PHOTOS,
			Permissions.PUBLISH_ACTION };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.login);
		showPackageInfo();

		simpleFacebook = SimpleFacebook.getInstance(this);
		simpleFacebook.logout(new OnLogoutListener() {

			@Override
			public void onFail(String reason) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onException(Throwable throwable) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onThinking() {
				// TODO Auto-generated method stub

			}

			@Override
			public void onLogout() {
				// TODO Auto-generated method stub

			}
		});

		final Button authButton = (Button) findViewById(R.id.auth_button);
		authButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				Utils.showProgressDialog(LoginFragment.this, "", "Logging in");

				signInWithFacebook();
			}
		});

	}

	private void showPackageInfo() {
		try {
			PackageInfo info = getPackageManager().getPackageInfo(
					"com.yamaha.saferide", PackageManager.GET_SIGNATURES);
			for (Signature signature : info.signatures) {
				MessageDigest md = MessageDigest.getInstance("SHA");
				md.update(signature.toByteArray());
				final String s = Base64.encodeToString(md.digest(),
						Base64.DEFAULT);
				Log.d("YOURHASH KEY:", s);
			}

		} catch (NameNotFoundException e) {

		} catch (NoSuchAlgorithmException e) {

		}
	}

	private void signInWithFacebook() {

		final Button authButton = (Button) findViewById(R.id.auth_button);
		authButton.setEnabled(false);

		final SimpleFacebookConfiguration configuration = new SimpleFacebookConfiguration.Builder()
				.setAppId(getResources().getString(R.string.app_id))
				.setNamespace("yamaha_bikemarket").setPermissions(permissions)
				.build();

		SimpleFacebook.setConfiguration(configuration);

		final OnLoginListener onLoginListener = new SimpleFacebook.OnLoginListener() {

			@Override
			public void onFail(String reason) {
				LogUtil.w("Facebook", reason);
				authButton.setEnabled(true);
			}

			@Override
			public void onException(Throwable throwable) {
				LogUtil.e("Facebook", "Bad thing happened", throwable);
				authButton.setEnabled(true);
			}

			@Override
			public void onThinking() {
				// show progress bar or something to the user while login is
				// happening
				LogUtil.i("Facebook", "In progress");
				Utils.showProgressDialog(LoginFragment.this, "",
						"Logging in...");

				final Button authButton = (Button) findViewById(R.id.auth_button);
				authButton.setEnabled(false);
			}

			@Override
			public void onLogin() {
				// change the state of the button or do whatever you want
				LogUtil.i("Facebook", "Logged in");
				handleGetFacebookInformation();
			}

			@Override
			public void onNotAcceptingPermissions() {
				LogUtil.w("Facebook", "User didn't accept read permissions");
				authButton.setEnabled(true);
			}

		};

		final OnLogoutListener onLogoutListener = new OnLogoutListener() {

			@Override
			public void onFail(String reason) {
				LogUtil.w("Facebook", "Facebook Error : " + reason);
			}

			@Override
			public void onException(Throwable throwable) {
				LogUtil.e("Facebook", throwable.getLocalizedMessage(),
						throwable);
			}

			@Override
			public void onThinking() {
				LogUtil.i("Facebook", "User didn't accept read permissions");
				final Button authButton = (Button) findViewById(R.id.auth_button);
				authButton.setEnabled(false);
			}

			@Override
			public void onLogout() {
				LogUtil.i("Facebook", "User didn't accept read permissions");
			}
		};

		// login
		simpleFacebook.login(onLoginListener);
		simpleFacebook.logout(onLogoutListener);
	}

	private void handleGetFacebookInformation() {
		final Button authButton = (Button) findViewById(R.id.auth_button);
		authButton.setEnabled(false);

		simpleFacebook
				.getProfile(new SimpleFacebook.OnProfileRequestListener() {

					@Override
					public void onFail(String reason) {
						Utils.closeAllDialog();
						authButton.setEnabled(true);
						LogUtil.w("Facebook GetProfile", "Fail : " + reason);
					}

					@Override
					public void onException(Throwable throwable) {
						Utils.closeAllDialog();
						authButton.setEnabled(true);
						LogUtil.e("Facebook GetProfile", "Bad thing happened",
								throwable);
					}

					@Override
					public void onThinking() {

						Utils.showProgressDialog(LoginFragment.this, "",
								"Logging in...");

						LogUtil.i("Facebook GetProfile", "In progress");
						final Button authButton = (Button) findViewById(R.id.auth_button);
						authButton.setEnabled(false);
					}

					@Override
					public void onComplete(Profile profile) {
						LogUtil.i("Facebook GetProfile", "Completed");
						String id = profile.getId();
						LogUtil.i("Facebook GetProfile", "Id : " + id);
						LogUtil.i("Facebook GetProfile",
								"Name : " + profile.getName());
						LogUtil.i("Facebook GetProfile",
								"Email : " + profile.getEmail());

						SCStaticFunc.setUserId(LoginFragment.this, id);
						doRegisterPush(profile);
					}
				});

	}

	private void doRegisterPush(final Profile profile) {

		// if (!isRegisterd) {
		// isRegisterd = true;
		// registerReceiver(mHandleMessageReceiver, new IntentFilter(
		// DISPLAY_MESSAGE_ACTION));
		// }

		// Make sure the device has the proper dependencies.
		GCMRegistrar.checkDevice(this);

		// Make sure the manifest was properly set - comment out this line
		// while developing the app, then uncomment it when it's ready.
		GCMRegistrar.checkManifest(this);

		// Get GCM registration id
		final String regId = GCMRegistrar.getRegistrationId(this);

		// Check if regid already presents
		if (regId.equals("")) {
			// Registration is not present, register now with GCM
			LogUtil.i("Push Notification", "Reg Id Is Nothing.");
			GCMRegistrar.register(this, CommonUtilities.SENDER_ID);
			doGetUserInfo(profile, "");
		} else {
			// Device is already registered on GCM
			if (GCMRegistrar.isRegisteredOnServer(this)) {
				// Skips registration.
				doGetUserInfo(profile, regId);
			} else {
				// Try to register again, but not in the UI thread.
				// It's also necessary to cancel the thread onDestroy(),
				// hence the use of AsyncTask instead of a raw thread.
				final Context context = this;
				mRegisterTask = new AsyncTask<Void, Void, Void>() {

					@Override
					protected Void doInBackground(Void... params) {
						// Register on our server
						// On server creates a new user
						LogUtil.i("Push Notification", "Get Reg Id : " + regId);
						doGetUserInfo(profile, regId);
						return null;
					}

					@Override
					protected void onPostExecute(Void result) {
						mRegisterTask = null;
					}

				};
				mRegisterTask.execute(null, null, null);
			}
		}
	}

	private void doGetUserInfo(final Profile profile, final String regId) {
		final Button authButton = (Button) findViewById(R.id.auth_button);
		authButton.setEnabled(false);

		Log.d(TAG, "FaceBook Access Token : " + simpleFacebook.getAccessToken());

		final RequestParams params = new RequestParams();
		params.put("user_id", profile.getId());
		params.put("email", profile.getEmail());
		params.put("firstname", profile.getFirstName());
		params.put("lastname", profile.getLastName());
		params.put("profile_image",
				"https://graph.facebook.com/" + profile.getId() + "/picture");
		params.put("at", simpleFacebook.getAccessToken());
		params.put("rid", regId);
		LogUtil.d("Get User Info", "Params : " + params.toString());

		final AsyncHttpClient client = new AsyncHttpClient();
		client.post(API.GET_USERINFO, params, new MyAsyncHttpResponseHandler(
				API.GET_USERINFO, this) {

			@Override
			public void onStart() {
				super.onStart();
				authButton.setEnabled(false);
			}

			@Override
			public void onSuccess(String res) {
				super.onSuccess(res);

				finish();
				overridePendingTransition(0, 0);
				final Intent intent = new Intent(LoginFragment.this,
						MainActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);

				Utils.closeAllDialog();
			}

			@Override
			public void onFailure(Throwable e, String error) {
				super.onFailure(e, error);
				Toast.makeText(LoginFragment.this, error, Toast.LENGTH_SHORT)
						.show();
			}

			@Override
			public void onFinish() {
				super.onFinish();
				authButton.setEnabled(true);
				Utils.closeAllDialog();
			}

		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		simpleFacebook.onActivityResult(this, requestCode, resultCode, data);
		super.onActivityResult(requestCode, resultCode, data);

	}

	@Override
	protected void onPause() {
		super.onPause();
		Utils.closeAllDialog();

		LogUtil.i("Login Activity", "onPause isRegisterd : " + isRegisterd);
		if (isRegisterd) {
			// unregisterReceiver(mHandleMessageReceiver);
			isRegisterd = false;
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		Utils.closeAllDialog();
		LogUtil.i("Login Activity", "onDestroy isRegisterd : " + isRegisterd);
		if (isRegisterd) {
			// unregisterReceiver(mHandleMessageReceiver);
			isRegisterd = false;
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		LogUtil.i("Login Activity", "onResume isRegisterd : " + isRegisterd);
		if (!isRegisterd) {
			isRegisterd = true;
			// registerReceiver(mHandleMessageReceiver, new IntentFilter(
			// DISPLAY_MESSAGE_ACTION));
		}
	}
}
